#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialogsettings.h"
#include "dialogreportpreview.h"
#include "../common/seller.h"

#include <QAxObject>
#include <QFileDialog>
#include <QDir>
#include <QTimer>
#include <QSettings>
#include <QMessageBox>
#include <QDebug>
#include "dialogsaleseditor.h"




bool MainWindow::loadPosFiles()
{
    QFile file;
    for (int row=0;row<ui->listWidgetPOSFiles->count ();row++)
    {

        file.setFileName (ui->listWidgetPOSFiles->item (row)->text ());
        if (!file.open (QFile::ReadOnly))
        {
            QMessageBox::critical (this,
                                   trUtf8 ("Problem beim Laden der POS Datei"),
                                   trUtf8 ("Die POS Datei %2 konnte nicht geladen werden!\nFehler: %1")
                                   .arg(file.errorString ())
                                   .arg(file.fileName ()));
            return false;
        }
        QString data=file.readAll ();
        QStringList rows=data.split("\n");
        rows.removeFirst ();
        rows.removeLast ();
        foreach(QString rowData,rows)
        {
            QStringList columnData=rowData.split(";");
            cs8Seller *seller;
            if (m_sellerModel->findItems (columnData.at(2),Qt::MatchExactly,0).count ()==0)
            {
                // add unknown seller
                int row=m_sellerModel->rowCount ();

                m_sellerModel->insertRow(row);
                m_sellerModel->setData (m_sellerModel->index (row,0),columnData.at(2));
                m_sellerModel->setData (m_sellerModel->index (row,1),"Unbekannt");
                seller=new cs8Seller(m_sellerModel);
                seller->setName ("Unbekannt");
                seller->clearSales ();
                m_sellerModel->setData (m_sellerModel->index (row,0),qVariantFromValue(const_cast<cs8Seller*>(seller)),Qt::UserRole);
                //seller=qVariantValue<cs8Seller *>(m_sellerModel->findItems (columnData.at(2),Qt::MatchExactly,0).at(0)->data (Qt::UserRole));
            }
            else
                seller=qVariantValue<cs8Seller *>(m_sellerModel->findItems (columnData.at(2),Qt::MatchExactly,0).at(0)->data (Qt::UserRole));

            qDebug() << seller->name ();
            //
            seller->addSale (QDateTime::fromString (columnData.at(1),Qt::ISODate),columnData.at(0),columnData.at(3).toInt (),columnData.at(4).toDouble ());
        }
        file.close ();
    }

    return true;
}

void MainWindow::calculateValues()
{
    double totalTurnOver=0;
    cs8ReportDataList turnOverPerDay;
    for (int row=0;row<m_sellerModel->rowCount ();row++)
    {
        cs8Seller *seller=qVariantValue<cs8Seller *>(m_sellerModel->item (row,0)->data (Qt::UserRole));
        if (seller->totalSum ()>0)
        {
            qDebug() << "seller: " << m_sellerModel->item(row,0)->text () << m_sellerModel->item (row,1)->text () << " turnover: " << seller->totalSum ();
            totalTurnOver += seller->totalSum ();
            foreach(sale *newSale,seller->sales ())
            {
                if (!turnOverPerDay.contains (newSale->pos ()))
                    turnOverPerDay.insert (newSale->pos (),cs8ReportData());

                if (!turnOverPerDay[newSale->pos ()].contains (newSale->timeStamp ().date ()))
                    turnOverPerDay[newSale->pos ()].insert (newSale->timeStamp ().date (),cs8SalePerDay());

                turnOverPerDay[newSale->pos ()][newSale->timeStamp ().date ()].qtyParts+=newSale->quantity ();
                turnOverPerDay[newSale->pos ()][newSale->timeStamp ().date ()].turnOver+=newSale->total ();
                turnOverPerDay[newSale->pos ()][newSale->timeStamp ().date ()].share+=newSale->total ()*m_shareValue/100;

                //QDate date=newSale->timeStamp ().date ();
                //if (!turnOverPerDay.contains (date))
                //    turnOverPerDay.insert (date,0);
                //turnOverPerDay[date]=turnOverPerDay[date]+newSale->total ();
            }
        }
    }
    qDebug() << "Total turn over: " << totalTurnOver;
    DialogReportPreview dialog;
    dialog.setListDays (m_listDays);
    dialog.setTotalTurnOver (totalTurnOver);
    dialog.setTurnOverPerDay (turnOverPerDay);
    dialog.setSharePercent (m_shareValue);
    dialog.setShareAbsolute (totalTurnOver*m_shareValue/100);
    for (int row=0;row<m_sellerModel->rowCount ();row++)
    {
        cs8Seller *seller=qVariantValue<cs8Seller *>(m_sellerModel->item (row,0)->data (Qt::UserRole));
        if (seller->totalSum ()!=0)
            dialog.addSeller(m_sellerModel->item (row,0)->text (),m_sellerModel->item (row,1)->text (),seller);
    }
    dialog.createPreview ();
    dialog.exec ();
}

bool MainWindow::createReport()
{
    // reset sellers' turnover
    m_sellerModel->clearSellersTurnOver ();
    loadPosFiles ();
    calculateValues ();
    return true;
}

void MainWindow::readSellersList()
{
    if (!m_sellerModel->readSellerList ("Verkaufsnummernliste.csv"))
    {
        QMessageBox::critical (this,
                               trUtf8 ("Problem"),
                               trUtf8 ("Die Verkäuferliste konnte nicht geladen werden!"
                                       "\nBitte überprüfen, dass die Datei \"%1\" vorhanden ist")
                               .arg("Verkaufsnummernliste.csv"));
    }
    ui->tableViewSellers->resizeColumnsToContents ();
}

void MainWindow::writeSettings()
{
    QSettings settings;
    settings.setValue ("shareValue",m_shareValue);
    settings.setValue ("listDays",m_listDays);
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QCoreApplication::setOrganizationName("Ingos Helfer");
    QCoreApplication::setApplicationName("FlohmarktPOS");

    ui->setupUi(this);

    m_sellerModel=new SellerModel(this);
    ui->tableViewSellers->setModel (m_sellerModel);

    QTimer::singleShot (0,this,SLOT(setup()));

}

MainWindow::~MainWindow()
{
    writeSettings ();
    delete ui;
}

void MainWindow::on_actionSchliessen_triggered()
{
    close();
}

void MainWindow::on_cbSelectPOSFiles_clicked()
{
    QStringList list=QFileDialog::getOpenFileNames (this,
                                                    trUtf8 ("POS Dateien auswählen"),
                                                    QDir::currentPath (),
                                                    QString("*.pos"));
    if (list.count ()!=0)
    {
        ui->listWidgetPOSFiles->clear ();
        ui->listWidgetPOSFiles->addItems (list);
    }
}


void MainWindow::setup()
{
    QDir dir;
    dir.setPath (QDir::currentPath ());
    QStringList list=dir.entryList (QStringList() << "*.pos");
    ui->listWidgetPOSFiles->addItems (list);

    QSettings settings;
    m_shareValue=settings.value ("shareValue",0).toInt ();
    m_listDays=settings.value ("listDays",false).toBool ();
    readSellersList ();
}


void MainWindow::on_cpExport_clicked()
{
    createReport();
}

void MainWindow::on_actionEinstellungen_triggered()
{
    DialogSettings dialog;
    dialog.setShare (m_shareValue);
    dialog.setListSalesAfterDays (m_listDays);
    if (dialog.exec ()==QDialog::Accepted)
    {
        m_shareValue=dialog.share ();
        m_listDays=dialog.listSalesAfterDays ();
    }
}

void MainWindow::on_listWidgetPOSFiles_doubleClicked(const QModelIndex &index)
{
    QString fileName=ui->listWidgetPOSFiles->item (index.row ())->text ();
    // open the editor
    DialogSalesEditor editor;
     editor.setSellerModel (m_sellerModel);
    editor.setPosFileName (fileName);

    editor.exec();
}
